package cn.zy.pet.service.impl;

import cn.zy.basic.exception.BusinessException;
import cn.zy.basic.service.IBaiduAiAuditService;
import cn.zy.basic.util.*;
import cn.zy.order.domain.OrderPetAcquisition;
import cn.zy.order.mapper.OrderPetAcquisitionMapper;
import cn.zy.org.domain.Employee;
import cn.zy.org.domain.Shop;
import cn.zy.org.mapper.EmployeeMapper;
import cn.zy.org.mapper.ShopMapper;
import cn.zy.pet.domain.SearchMasterMsg;
import cn.zy.pet.domain.SearchMasterMsgAuditLog;
import cn.zy.pet.dto.MsgDto;
import cn.zy.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.zy.pet.mapper.SearchMasterMsgMapper;
import cn.zy.pet.query.SearchMasterMsgQuery;
import cn.zy.pet.service.ISearchMasterMsgService;
import cn.zy.basic.service.impl.BaseServiceImpl;
import cn.zy.user.domain.Logininfo;
import cn.zy.user.domain.User;
import cn.zy.user.mapper.UserMapper;
import org.apache.poi.ss.formula.functions.Odd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id
        //        note      -   备注
        //1.添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLoginId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);//为了获得自增id,方便下面使用
        //2.百度AI智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
        if(boo1 && boo2){//审核通过
            msg.setState(1);
            msg.setNote("审核通过！！！");
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核通过");
            searchMasterMsgAuditLogMapper.save(log);
            //获取用户最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if(nearestShop!=null){
                msg.setShopId(nearestShop.getId());
                //发消息 - 店铺
                //SmsUtils.sendSms(nearestShop.getTel(),"您有新的订单,请尽快去"+msg.getAddress()+"处理。");
                System.out.println("【"+nearestShop.getName()+"】"+"您有新的订单,请尽快去"+msg.getAddress()+"处理。");
            }else {//50公里内,没有找到最近的店铺
                msg.setState(3);//放入寻主池
                //发消息 - 用户
                //SmsUtils.sendSms(logininfo.getPhone(),"您附近暂时没有店铺,请耐心等待。。。");
                System.out.println("您附近暂时没有店铺,请耐心等待。。。");
            }
            searchMasterMsgMapper.update(msg);
            //return 前端
            return new AjaxResult();
        }else {//审核不通过
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //发消息 - 用户
            //SmsUtils.sendSms(logininfo.getPhone(),"寻主消息发送失败,请修改后重新发送。。。");
            System.out.println("寻主消息发布失败,请修改后重新发送。。。");
            //删除寻主消息
            searchMasterMsgMapper.del(msg.getId());
            return AjaxResult.me().setSuccess(false).setMsg("寻主消息发送失败,请修改后重新发布。。。");
        }
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        //获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        //获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLoginId(logininfo.getId());
        //将用户id添加到query,方便返回到前端使用userId查询用户自己发布的寻主消息
        query.setUserId(user.getId());

        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        //拒单:平台已经把寻主消息分配给店铺,店铺因某些原因不想接单
        //拒单之后:放入寻主池,将店铺id置空
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(MsgDto msgDto) {
        //平台将寻主消息分给了这个店铺
        //店铺接收了,指派一个人去接收宠物
        //1.判断订单是否存在 - 如果存在 - 说明有人在处理 - 提示不要重复接单
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgDto.getMsgId());
        //state==0，如果2天内没有去接，订单处于-1取消状态，并且数据库有该订单
        if(order!=null&&order.getState()==0){
            throw new BusinessException("该订单正在处理,请勿重复接单!");
        }

        //2.生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgDto.getMsgId());
        OrderPetAcquisition newOrder = createOrder(msg,msgDto);
        orderPetAcquisitionMapper.save(newOrder);

        //3.告诉处理人在规定时间内去接回宠物:发短信 - 2天
        Employee employee = employeeMapper.loadById(msgDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"您有新的订单,请在两天内前往"+msg.getAddress()+"接回宠物");
        System.out.println("【"+employee.getUsername()+"】您有新的订单,请在两天内前往"+msg.getAddress()+"接回宠物");
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(msgDto.getNote());
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
        //order.setState(); - 正在处理 - 实体类默认0待处理
        //order.setPaytype(); - 接宠物的时候设置
        //order.setPetId(); - 宠物接回来后设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());

        return order;
    }
}
